<template>
	<el-dialog v-model="dialogVisible" :title="$t('order.weihuwul')" width="700" :before-close="handleClose">
		<div>
			<el-button type="primary" size="small" @click="addRow" style="margin-bottom: 10px">{{ $t('material.add') }}</el-button>
			<el-table :data="tableData" border style="width: 100%; margin-bottom: 10px">
				<el-table-column prop="materialCode" :label="$t('agv.materialCode')">
					<template #default="scope">
            			<MaterialSelect style="width: 260px" v-model="scope.row.materialCode" @change="val => changeMaterial(val, scope.row)" />
					</template>
				</el-table-column>
				<el-table-column prop="materialName" :label="$t('agv.materialName')">
					<template #default="scope">
						<el-input v-model="scope.row.materialName" :placeholder="$t('client.inputResourceIdsTip')" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('common.action')" width="80">
          <template #default="scope">
            <el-button  type="danger" size="small" @click="removeRow(scope)">{{ $t('common.delBtn') }}</el-button>
          </template>
        </el-table-column>
			</el-table>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" v-loading="loading" @click="onConfirm">{{$t('user.logOutConfirm')}}</el-button>
				<el-button  @click="handleClose">  {{$t('user.logOutCancel')}} </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import {getDicItemByCode, createAbroadMaterial, deleteAbroadMaterial} from '/@/api/platform/mes/wmsCheckstock';
import { ElMessage } from 'element-plus';
import { ref, reactive } from 'vue';
import MaterialSelect from "/@/components/mes/select/MaterialSelect.vue";
import {useI18n} from 'vue-i18n';

const {t} = useI18n();

const dialogVisible = ref(false);
const from = reactive({});
const loading = ref(false);
const tableData = ref([]);

const handleClose = () => {
	dialogVisible.value = false;
	tableData.value = [];
	Object.keys(from).forEach(key => from[key] = '');
};
const handleOpen = (row, text) => {
	getDicItemByCodeData();
	dialogVisible.value = true;
};
// 获取数据
const getDicItemByCodeData = async () => {
	let res = await getDicItemByCode({
		code: 'PoAbroadMaterial',
	});
	if (res.ok) {
    tableData.value = res.data.map(item => {
      return {
	    id: item.id,
        materialCode: item.value,
        materialName: item.text,
        isNew: false
      }
    });
	}
};

//生成随机id
const generateRandomNum = () => {
	const timestamp = new Date().getTime();
	const randomNum = uuid();
	return timestamp.toString() + '-' + randomNum.toString();
};
const uuid = () => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = (Math.random() * 16) | 0,
			v = c == 'x' ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
};

const addRow = () => {
  tableData.value.push({id: generateRandomNum(), materialCode: '', materialName: '', isNew: true });
  console.log("tableData",tableData.value);
};
const removeRow = async (row: any) => {
	if (!row.row.isNew) {
		try {
			// 删除
			var res = await deleteAbroadMaterial({ id: row.row.id});
			if(res.ok){
				ElMessage.success(t('common.delSuccessText'));
				await getDicItemByCodeData();
			}
		} catch (e) {
			ElMessage.warning(e.msg);
		}
	} else {
		// row.value.forEach((element) => {
		// 	var index = state.dataList?.map((m) => m.id).indexOf(element.id);
		// 	if (index !== -1) {
		// 		state.dataList.splice(index, 1);
		// 	}
		// });

		//根据row.row.id 删除tableData中的数据
		// console.log("row.row.id",row.row.id);
		// var index = tableData.value?.map((m) => m.id).indexOf(row.row.id);
		// console.log("index",index);
		// 	if (index !== -1) {
		// 		tableData.value.splice(index, 1);
		// 		console.log("tableData.value",tableData.value);
		// 	}
		// console.log("row.row.id",row.row.id);
		// console.log("index",row.index);
		// tableData.value.splice(row.$index, 1);
		// console.log("tableData.value",tableData.value);
		// 删除未保存的临时数据（前端删除）
		// tableData.value = tableData.value.filter(
		// 	(item: any) => item.id !== row.row.id
		// );
		const index = tableData.value.findIndex(item => item.id === row.row.id);
		if (index !== -1) {
			tableData.value.splice(index, 1);
		}
	}
};

const onConfirm = async () => {
	await createDate();
};

const createDate = async () => {
  loading.value = true;
  try {
    const params = {
      materialCode: tableData.value.filter(item => item.isNew)
    };
	//如果tableData数组内任意一组materialCode为空，则提示
	if (params.materialCode.some(item => item.materialCode === '')) {
	  ElMessage.warning(t('order.msg5'));
	  return;
	}

	console.log("params",params);
    let res = await createAbroadMaterial(params);
    if (res.ok) {
      ElMessage.success(t('common.optSuccessText'));
      dialogVisible.value = false;
    }
  } finally {
    loading.value = false;
  }
};

const changeMaterial = (val, row) => {
  if (val) {
    row.materialCode = val.materialCode;
    row.materialName = val.materialName;
  } else {
    row.materialCode = '';
    row.materialName = '';
  }
};

// 暴露handleOpen方法
defineExpose({
	handleOpen,
});
</script>

<style scoped lang="scss"></style>
